import Vue from 'vue'

import Cookies from 'js-cookie'

import 'normalize.css/normalize.css' // A modern alternative to CSS resets

import Element from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'

import '@/styles/element-variables.scss'
import '@/styles/index.scss' // global css
import '@/styles/dts.scss'

import App from './App'
import router from './router'
import store from './store'

import i18n from './lang' // Internationalization
import './icons' // icon
import './permission' // permission control

import * as filters from './filters' // global filters

import permission from '@/directive/permission/index.js' // 权限判断指令

// const originalRemoveTabindex = ElementUI.Dropdown.methods.removeTabindex;
// ElementUI.Dropdown.methods.removeTabindex = function() {
//   // 自定义逻辑
//   console.log('Custom removeTabindex');
//   originalRemoveTabindex.call(this); // 可选：调用原方法
// };

// 拿到 Element 内部的 Utils
const { PopupManager, Dropdown } = Element
// 2. 再包一层安全判断
if (PopupManager && PopupManager.removeTabindex) {
  const raw = PopupManager.removeTabindex
  PopupManager.removeTabindex = el => el && raw(el)
}
if (Dropdown && Dropdown.removeTabindex) {
  const raw = Dropdown.removeTabindex
  Dropdown.removeTabindex = el => el && raw(el)
}
// 如果还有 clickoutside 报错，顺带一起防
const oldHandler = Element.Clickoutside?._handler
if (oldHandler){
  Element.Clickoutside._handler = function (e) {
    try { oldHandler(e) } catch (_) { /* ignore */ }
  }
}

Vue.use(Element, {
  size: Cookies.get('size') || 'medium', // set element-ui default size
  i18n: (key, value) => i18n.t(key, value)
})

// 自定义 clickoutside 指令
Vue.directive('clickoutside', {
  bind(el, binding, vnode) {
    function documentHandler(e) {
      if (el.contains(e.target)) {
        return false;
      }
      if (binding.expression) {
        binding.value(e);
      }
    }
    el.__vueClickOutside__ = documentHandler;
    document.addEventListener('click', documentHandler);
  },
  unbind(el) {
    document.removeEventListener('click', el.__vueClickOutside__);
    delete el.__vueClickOutside__;
  }
});

Vue.directive('permission', permission)

// register global utility filters.
Object.keys(filters).forEach(key => {
  Vue.filter(key, filters[key])
})

Vue.config.productionTip = false

new Vue({
  el: '#app',
  router,
  store,
  i18n,
  render: h => h(App)
})
